#include "mkfiletablemodel.h"

#include "mkcore/mkcore.h"
#include "mkcore/mksettings.h"

#include <QFile>
#include <QDateTime>

#include <QDebug>

const quint32 MagicNumber = 0xff87dc56;
const quint16 FormatNumber = 0x0100;

MKFileTableModel::MKFileTableModel(QObject *parent) : MKTableModel(parent)
{
}

bool MKFileTableModel::removeRows(int row, int count, const QModelIndex &)
{
	beginRemoveRows(QModelIndex(), row, row + count - 1);
	for (int i = 0; i < count; ++i)
	{
		mRecords.removeAt(row);
		QModelIndex leftTop = index(row, C_Type);
		QModelIndex rightBottom = index(row, C_Cost);
		emit dataChanged(leftTop, rightBottom);
	}
	endRemoveRows();
	return true;
}

bool MKFileTableModel::save(const QString &fileName)
{
	if (!fileName.isEmpty())
	{
		mFileName = fileName;
	}

	if (mFileName.isEmpty())
	{
		qDebug() << "*** MKFileTableModel saveToFile() error: no filename secified";
		return false;
	}

	QFile file(mFileName);
	if (!file.open(QIODevice::WriteOnly))
	{
		qDebug() << "*** MKFileTableModel saveToFile() error: " + file.errorString();
		return false;
	}

	QDataStream out(&file);
	out << MagicNumber << FormatNumber;
	out.setVersion(QDataStream::Qt_4_4);
	QListIterator<RecordItem> i(mRecords);
	while (i.hasNext())
	{
		out << i.next();
	}

	return true;
}

bool MKFileTableModel::load(const QString &fileName)
{
	clear();
	if (fileName.isEmpty())
	{
		qDebug() << "*** MKFileTableModel loadFromFile() error: no filename secified";
		return false;
	}

	mFileName = fileName;

	QFile file(mFileName);
	if (!file.open(QIODevice::ReadOnly))
	{
		qDebug() << "*** MKFileTableModel loadFromFile() error: " + file.errorString();
		return false;
	}

	QDataStream in(&file);
	quint32 magicNumber;
	quint16 formatNumber;
	in >> magicNumber >> formatNumber;

	if (magicNumber!=MagicNumber)
	{
		qDebug() << "*** MKFileTableModel loadFromFile() error: unrecognized file type";
		return false;
	}

	if (formatNumber > FormatNumber)
	{
		qDebug() << "*** MKFileTableModel loadFromFile() error: file format version is too new";
		return false;
	}

	in.setVersion(QDataStream::Qt_4_4);

	RecordItem record;
	while(!in.atEnd())
	{
		in >> record;
		mRecords << record;
	}
	reset();
	return true;
}

quint32 MKFileTableModel::lastRecordId()
{
	quint32 lastRecordId = 0;

	QListIterator<RecordItem> i(mRecords);
	while (i.hasNext())
	{
		quint32 currentrecordId = i.next().id;
		if (currentrecordId > lastRecordId )
		{
			lastRecordId = currentrecordId;
		}
	}
	return lastRecordId;
}
